package com.rfid.a252robot.task;

import com.rfid.a252robot.event.OffShelfEvent;
import com.rfid.a252robot.net.BoxLibApi;
import com.rfid.a252robot.net.bean.UploadBook;
import com.rfid.db.bean.Book;
import com.rfid.db.bean.FailBook;
import com.rfid.db.bean.OperateInfo;
import com.rfid.manager.DBManager;
import com.rfid.manager.DoorBoxManager;
import com.rfid.manager.ReadTagManager;
import com.rfid.util.Util;
import com.shrfid.module_base.entity.TagEntity;
import com.spectre.generate.ConfigManager;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class OffShelfTask implements Runnable {

    boolean isAll;
    int boxNum;
    Executor mExecutor = Executors.newSingleThreadExecutor();
    public OffShelfTask(int boxNum,boolean all) {
        this.boxNum = boxNum;
        isAll = all;
    }

    @Override
    public void run() {
        try {
            if (isAll) {
                /**如果读写器与门锁都工作不正常，则流程结束后默认全部下架。
                 * 先选出天线对应的所有箱子，再得到这些箱子里面门关闭了的箱子里的书
                 * 更新：不管门关没关了，只要书取走了就算
                 * */
//                DoorBoxManager.INSTANCE.openAllLock();
                for (int i = 1; i <= 4; i++) {
                    ReadTagManager.INSTANCE.selectAntenna(i);
                    List<Book> books = new ArrayList<>();
                    List<Book> leftBooks = new ArrayList<>();
                    List<Integer> boxes = Util.getBoxes(i);
                    for (int boxNum : boxes) {
                        List<Book> bs = DBManager.getBooks(boxNum);
                        if (bs.size() == 0) {
                            continue;
                        }
//                        int open = DoorBoxManager.INSTANCE.getLockOpenStatus(boxNum);
//                        System.out.println("open = " + open);
//                        if (open == 0) {
                            books.addAll(bs);
//                        } else if (open == -1) {
//                            //出问题的，以后考虑
//                        } else if (open == 1) {
//                            //没关门的，这里需要有个后续处理,比如后面再另一个任务检测
//                        }
                    }
                    if (books.size() == 0) {
                        continue;
                    }
                    /**
                     * 天线读取5次，前面得到的书减去这次读取到的，剩下的认为是取走的
                     * */
                    int times = ConfigManager.INSTANCE.getGlobalConfig().getReadCount();
                    for (int j = 0; j < times; j++) {
                        List<TagEntity> tagEntities = ReadTagManager.INSTANCE.readTags();
                        for (TagEntity tagEntity : tagEntities) {
                            String barcode = tagEntity.getBookNo();
                            for (Book book : books) {
                                if (book.getBarcode().equals(barcode)) {
                                    if (!leftBooks.contains(book)) {
                                        leftBooks.add(book);
                                    }
                                    break;
                                }
                            }
                        }
                    }
                    books.removeAll(leftBooks);
                    for (Book book : books) {
                        DBManager.deleteBook(book);
                        DBManager.addOperateLog(book, OperateInfo.OPERATE_ADMIN_OFFSHELF);
                        sendInfoToServer(book);
                        FailBook fb = DBManager.getFailBook(book.getBarcode());
                        if (fb != null) {
                            DBManager.deleteFailBook(fb);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("send OffShelfEvent");
            EventBus.getDefault().post(new OffShelfEvent());
        }
    }

    private void sendInfoToServer(Book book) {
        mExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    BoxLibApi.INSTANCE.deleteBook(book, UploadBook.TYPE_ADMIN);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
